import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Statistic,
  Progress,
  Table,
  List,
  Avatar,
  Badge,
  Space,
  Typography,
  Button,
  Select,
  DatePicker,
  Alert,
  Spin,
  Tag,
  Tooltip
} from 'antd';
import {
  UserOutlined,
  ShoppingOutlined,
  FundOutlined,
  DollarOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  FullscreenOutlined
} from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

interface DashboardData {
  overview: {
    totalUsers: number;
    totalProducts: number;
    totalAssets: number;
    totalRevenue: number;
    userGrowth: number;
    productGrowth: number;
    assetGrowth: number;
    revenueGrowth: number;
  };
  systemStatus: {
    cpuUsage: number;
    memoryUsage: number;
    diskUsage: number;
    networkStatus: 'normal' | 'warning' | 'error';
    apiResponseTime: number;
    errorRate: number;
  };
  recentActivities: Array<{
    id: string;
    type: 'user' | 'product' | 'transaction' | 'system';
    title: string;
    description: string;
    time: string;
    status: 'success' | 'warning' | 'error' | 'info';
    user?: string;
  }>;
  alerts: Array<{
    id: string;
    level: 'high' | 'medium' | 'low';
    title: string;
    description: string;
    time: string;
    resolved: boolean;
  }>;
  chartData: {
    userTrend: Array<{ date: string; count: number; type: string }>;
    revenueTrend: Array<{ date: string; revenue: number; profit: number }>;
    productDistribution: Array<{ type: string; count: number; percentage: number }>;
  };
}

const AdminDashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);
  const [refreshing, setRefreshing] = useState(false);
  
  const dispatch = useDispatch();
  const user = useSelector((state: any) => state.auth.user);

  // 模拟数据加载
  useEffect(() => {
    loadDashboardData();
  }, [dateRange]);

  const loadDashboardData = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockData: DashboardData = {
        overview: {
          totalUsers: 12580,
          totalProducts: 156,
          totalAssets: 2580000000,
          totalRevenue: 15600000,
          userGrowth: 12.5,
          productGrowth: 8.3,
          assetGrowth: 15.2,
          revenueGrowth: 22.1
        },
        systemStatus: {
          cpuUsage: 65,
          memoryUsage: 78,
          diskUsage: 45,
          networkStatus: 'normal',
          apiResponseTime: 120,
          errorRate: 0.02
        },
        recentActivities: [
          {
            id: '1',
            type: 'user',
            title: '新用户注册',
            description: '用户 张三 完成注册并通过实名认证',
            time: '2024-01-15 14:30:00',
            status: 'success',
            user: '张三'
          },
          {
            id: '2',
            type: 'product',
            title: '产品上线',
            description: '新产品"稳健增长基金"已上线',
            time: '2024-01-15 13:45:00',
            status: 'info'
          },
          {
            id: '3',
            type: 'transaction',
            title: '大额交易',
            description: '用户 李四 购买产品，金额 ¥500,000',
            time: '2024-01-15 12:20:00',
            status: 'warning',
            user: '李四'
          },
          {
            id: '4',
            type: 'system',
            title: '系统维护',
            description: '定时任务执行完成，数据同步正常',
            time: '2024-01-15 11:00:00',
            status: 'success'
          }
        ],
        alerts: [
          {
            id: '1',
            level: 'high',
            title: '系统负载过高',
            description: 'CPU使用率超过80%，建议检查系统性能',
            time: '2024-01-15 14:25:00',
            resolved: false
          },
          {
            id: '2',
            level: 'medium',
            title: '异常登录检测',
            description: '检测到异地登录行为，已发送验证邮件',
            time: '2024-01-15 13:15:00',
            resolved: true
          }
        ],
        chartData: {
          userTrend: [
            { date: '2024-01-01', count: 1200, type: '新增用户' },
            { date: '2024-01-02', count: 1350, type: '新增用户' },
            { date: '2024-01-03', count: 1180, type: '新增用户' },
            { date: '2024-01-04', count: 1420, type: '新增用户' },
            { date: '2024-01-05', count: 1580, type: '新增用户' },
            { date: '2024-01-01', count: 11200, type: '活跃用户' },
            { date: '2024-01-02', count: 11350, type: '活跃用户' },
            { date: '2024-01-03', count: 11180, type: '活跃用户' },
            { date: '2024-01-04', count: 11420, type: '活跃用户' },
            { date: '2024-01-05', count: 11580, type: '活跃用户' }
          ],
          revenueTrend: [
            { date: '2024-01-01', revenue: 1200000, profit: 240000 },
            { date: '2024-01-02', revenue: 1350000, profit: 270000 },
            { date: '2024-01-03', revenue: 1180000, profit: 236000 },
            { date: '2024-01-04', revenue: 1420000, profit: 284000 },
            { date: '2024-01-05', revenue: 1580000, profit: 316000 }
          ],
          productDistribution: [
            { type: '股票型基金', count: 45, percentage: 28.8 },
            { type: '债券型基金', count: 38, percentage: 24.4 },
            { type: '混合型基金', count: 32, percentage: 20.5 },
            { type: '货币型基金', count: 25, percentage: 16.0 },
            { type: '其他', count: 16, percentage: 10.3 }
          ]
        }
      };
      
      setDashboardData(mockData);
    } catch (error) {
      console.error('加载仪表盘数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    await loadDashboardData();
    setRefreshing(false);
  };

  const getActivityIcon = (type: string) => {
    const iconMap = {
      user: <UserOutlined />,
      product: <ShoppingOutlined />,
      transaction: <FundOutlined />,
      system: <CheckCircleOutlined />
    };
    return iconMap[type as keyof typeof iconMap] || <ClockCircleOutlined />;
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      success: '#52c41a',
      warning: '#faad14',
      error: '#ff4d4f',
      info: '#1890ff'
    };
    return colorMap[status as keyof typeof colorMap] || '#d9d9d9';
  };

  const getAlertColor = (level: string) => {
    const colorMap = {
      high: 'error',
      medium: 'warning',
      low: 'info'
    };
    return colorMap[level as keyof typeof colorMap] || 'default';
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!dashboardData) {
    return (
      <Alert
        message="数据加载失败"
        description="无法加载仪表盘数据，请稍后重试"
        type="error"
        showIcon
        action={
          <Button size="small" onClick={loadDashboardData}>
            重试
          </Button>
        }
      />
    );
  }

  const { overview, systemStatus, recentActivities, alerts, chartData } = dashboardData;

  return (
    <div>
      {/* 页面标题和操作栏 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div>
          <Title level={2} style={{ margin: 0 }}>仪表盘</Title>
          <Text type="secondary">欢迎回来，{user?.username || '管理员'}！</Text>
        </div>
        <Space>
          <RangePicker
            value={dateRange}
            onChange={(dates) => dates && setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs])}
            format="YYYY-MM-DD"
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={refreshing}
          >
            刷新
          </Button>
          <Button icon={<FullscreenOutlined />}>全屏</Button>
        </Space>
      </div>

      {/* 概览统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={overview.totalUsers}
              precision={0}
              valueStyle={{ color: '#3f8600' }}
              prefix={<UserOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  +{overview.userGrowth}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="产品总数"
              value={overview.totalProducts}
              precision={0}
              valueStyle={{ color: '#1890ff' }}
              prefix={<ShoppingOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  +{overview.productGrowth}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="管理资产"
              value={overview.totalAssets}
              precision={0}
              valueStyle={{ color: '#722ed1' }}
              prefix={<FundOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  +{overview.assetGrowth}%
                </span>
              }
              formatter={(value) => `¥${(Number(value) / 100000000).toFixed(1)}亿`}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总收入"
              value={overview.totalRevenue}
              precision={0}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<DollarOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  +{overview.revenueGrowth}%
                </span>
              }
              formatter={(value) => `¥${(Number(value) / 10000).toFixed(1)}万`}
            />
          </Card>
        </Col>
      </Row>

      {/* 系统状态监控 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={12}>
          <Card title="系统状态" extra={<Badge status="processing" text="运行中" />}>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div style={{ textAlign: 'center' }}>
                  <Progress
                    type="circle"
                    percent={systemStatus.cpuUsage}
                    size={80}
                    status={systemStatus.cpuUsage > 80 ? 'exception' : 'normal'}
                  />
                  <div style={{ marginTop: 8 }}>CPU使用率</div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ textAlign: 'center' }}>
                  <Progress
                    type="circle"
                    percent={systemStatus.memoryUsage}
                    size={80}
                    status={systemStatus.memoryUsage > 85 ? 'exception' : 'normal'}
                  />
                  <div style={{ marginTop: 8 }}>内存使用率</div>
                </div>
              </Col>
            </Row>
            <div style={{ marginTop: 16 }}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>磁盘使用率</Text>
                  <Text>{systemStatus.diskUsage}%</Text>
                </div>
                <Progress percent={systemStatus.diskUsage} size="small" />
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>API响应时间</Text>
                  <Text>{systemStatus.apiResponseTime}ms</Text>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>错误率</Text>
                  <Text style={{ color: systemStatus.errorRate > 0.05 ? '#ff4d4f' : '#52c41a' }}>
                    {(systemStatus.errorRate * 100).toFixed(2)}%
                  </Text>
                </div>
              </Space>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="系统告警" extra={<Badge count={alerts.filter(a => !a.resolved).length} />}>
            <List
              size="small"
              dataSource={alerts.slice(0, 5)}
              renderItem={(item) => (
                <List.Item key={item.id}>
                  <List.Item.Meta
                    avatar={
                      <Badge 
                        status={item.resolved ? 'default' : 'error'} 
                        dot
                      />
                    }
                    title={
                      <Space>
                        <Tag color={getAlertColor(item.level)}>{item.level.toUpperCase()}</Tag>
                        <Text style={{ textDecoration: item.resolved ? 'line-through' : 'none' }}>
                          {item.title}
                        </Text>
                      </Space>
                    }
                    description={
                      <div>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {item.description}
                        </Text>
                        <br />
                        <Text type="secondary" style={{ fontSize: 11 }}>
                          {item.time}
                        </Text>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={16}>
          <Card title="用户趋势" extra={<Button size="small">查看详情</Button>}>
            <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fafafa', borderRadius: 6 }}>
              <Text type="secondary">用户趋势图表 (需要安装图表库)</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="产品分布" extra={<Button size="small">查看详情</Button>}>
            <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fafafa', borderRadius: 6 }}>
              <Text type="secondary">产品分布饼图 (需要安装图表库)</Text>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 最近活动 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={16}>
          <Card title="收入趋势" extra={<Button size="small">查看详情</Button>}>
            <div style={{ height: 250, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fafafa', borderRadius: 6 }}>
              <Text type="secondary">收入趋势柱状图 (需要安装图表库)</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="最近活动" extra={<Button size="small">查看全部</Button>}>
            <List
              size="small"
              dataSource={recentActivities.slice(0, 6)}
              renderItem={(item) => (
                <List.Item key={item.id}>
                  <List.Item.Meta
                    avatar={
                      <Avatar 
                        size="small" 
                        style={{ backgroundColor: getStatusColor(item.status) }}
                        icon={getActivityIcon(item.type)}
                      />
                    }
                    title={
                      <Text style={{ fontSize: 13 }}>{item.title}</Text>
                    }
                    description={
                      <div>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {item.description}
                        </Text>
                        <br />
                        <Text type="secondary" style={{ fontSize: 11 }}>
                          {item.time}
                        </Text>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AdminDashboard;